package com.qsign.sfrz_android.activity.home.ViewController;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.qsign.sfrz_android.R;
import com.qsign.sfrz_android.base.NewBaseActivity;
import com.qsign.sfrz_android.net.IServiceImpl;
import com.qsign.sfrz_android.net.RequestServiceImpl;
import com.qsign.sfrz_android.publicview.SimpleDialog;
import com.qsign.sfrz_android.utils.BaseUtil;
import com.zhy.autolayout.utils.AutoUtils;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ChuKuMainActivity extends NewBaseActivity {
    @BindView(R.id.pihaoedit)
    EditText pihaoedit;
    @BindView(R.id.shadanedit)
    EditText shadanedit;
    @BindView(R.id.recyclerview)
    RecyclerView recyclerview;
    QuickAdapter quickAdapter;
    ArrayList<String> arrayList = new ArrayList<>();
    @BindView(R.id.nextbtn)
    Button nextbtn;
    String LX="";
    private final static String SCAN_ACTION = "scan.rcv.message";
    @Override
    protected void initTitle(TextView textView) {
        textView.setText("托盘出库");
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_chuku_main;
    }


    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(mScanReceiver);
    }

    @Override
    protected void onResume() {
        super.onResume();
        IntentFilter filter = new IntentFilter();
        filter.addAction(SCAN_ACTION);
        registerReceiver(mScanReceiver, filter);

        if(shadanedit.getEditableText().toString().length()>0){
            showWait();
            RequestServiceImpl.sd_query(mMIPHandler, IServiceImpl.SHADAN_QUERY, shadanedit.getEditableText().toString());
        }else if(pihaoedit.getEditableText().toString().length()>0){
            showWait();
            RequestServiceImpl.ph_query(mMIPHandler, IServiceImpl.PH_QUERY, pihaoedit.getEditableText().toString());
        }
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);

        GridLayoutManager layoutManager = new GridLayoutManager(this, 4);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerview.setLayoutManager(layoutManager);
        //给RecyclerView设置适配器
        quickAdapter = new QuickAdapter();
        recyclerview.setAdapter(quickAdapter);
        recyclerview.setHasFixedSize(true);
        recyclerview.setNestedScrollingEnabled(false);


        shadanedit.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event != null
                        && event.getKeyCode() == KeyEvent.KEYCODE_ENTER
                        && event.getAction() == KeyEvent.ACTION_UP) {
                    String monadNo = shadanedit.getText().toString().trim();
                    if (monadNo.length() >= 4) {
                        showWait();
                        RequestServiceImpl.sd_query(mMIPHandler, IServiceImpl.SHADAN_QUERY, shadanedit.getEditableText().toString());
                    }
                    return true;
                }
                return false;
            }
        });

        pihaoedit.setOnFocusChangeListener(new android.view.View.
                OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    nextbtn.setEnabled(false);
                    arrayList.clear();
                    quickAdapter.notifyDataSetChanged();
                    shadanedit.setText("");
                }
            }
        });

        shadanedit.setOnFocusChangeListener(new android.view.View.
                OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    nextbtn.setEnabled(false);
                    arrayList.clear();
                    quickAdapter.notifyDataSetChanged();
                    pihaoedit.setText("");
                }
            }
        });

        pihaoedit.setFocusableInTouchMode(true);
        pihaoedit.requestFocus();
    }
    private BroadcastReceiver mScanReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            if(shadanedit.hasFocus()){
                byte[] barocode = intent.getByteArrayExtra("barocode");
                int barocodelen = intent.getIntExtra("length", 0);
                String barcodeStr = new String(barocode, 0, barocodelen);
                shadanedit.setText(barcodeStr);
                showWait();
                RequestServiceImpl.sd_query(mMIPHandler, IServiceImpl.SHADAN_QUERY, shadanedit.getEditableText().toString());
            }

        }
    };
    public class QuickAdapter extends BaseQuickAdapter<String, BaseViewHolder> {
        public QuickAdapter() {
            super(R.layout.chuku_item, arrayList);
        }

        @Override
        protected BaseViewHolder createBaseViewHolder(View view) {
            AutoUtils.auto(view);
            return super.createBaseViewHolder(view);
        }

        @Override
        protected void convert(BaseViewHolder holder, final String item) {
            TextView chuku_item = holder.getView(R.id.chuku_item);
            chuku_item.setText(item);
        }
    }

    @OnClick({R.id.querybtn, R.id.nextbtn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.querybtn:
                if (pihaoedit.getEditableText().toString().length() == 0) {
                    BaseUtil.ShowToast(this, "请输入批号");
                    return;
                }
                showWait();
                RequestServiceImpl.ph_query(mMIPHandler, IServiceImpl.PH_QUERY, pihaoedit.getEditableText().toString());

                break;
            case R.id.nextbtn:
                Intent intent=new Intent(this,ChuKuActivity.class);
                intent.putExtra("LX",LX);
                if(LX.equals("PH")){
                    intent.putExtra("bizno",pihaoedit.getEditableText().toString().trim());
                }else if(LX.equals("SD")){
                    intent.putExtra("bizno",shadanedit.getEditableText().toString().trim());
                }
                startActivity(intent);

                break;
        }
    }

    @Override
    public void onPostHandle(int requestType, Object objBody, boolean error) throws Exception {
        stopWait();
        String msg = "";
        String opt = "";
        switch (requestType) {
            case IServiceImpl.PH_QUERY://根据条件查询
                try {
                    JSONObject jsonObject = JSONObject.parseObject(objBody.toString());
                    msg = jsonObject.getString("MSG_INFO");
                    opt = jsonObject.getString("OPT_FLAG");
                    arrayList.clear();
                    if ("SUCCESS".equals(opt)) {
                        JSONArray dataarray = jsonObject.getJSONArray("DATA");
                        if (dataarray != null && dataarray.size() > 0) {
                            for (int i = 0; i < dataarray.size(); i++) {
                                arrayList.add(dataarray.getJSONObject(i).getString("WHLOC"));
                            }
                            shadanedit.setText("");
                            LX="PH";
                            nextbtn.setEnabled(true);
                        }else{
                            nextbtn.setEnabled(false);
                        }
                        quickAdapter.notifyDataSetChanged();
                        quickAdapter.setEmptyView(R.layout.empty, (ViewGroup) recyclerview.getParent());
                    } else {
                        if (TextUtils.isEmpty(msg)) {
                            showSimpleDialog("查询出错");
                        } else {
                            showSimpleDialog(msg);
                        }
                        pihaoedit.setText("");
                        nextbtn.setEnabled(false);
                    }

                } catch (Exception e) {
                }

                break;
            case IServiceImpl.SHADAN_QUERY:
                try {
                    JSONObject jsonObject = JSONObject.parseObject(objBody.toString());
                    msg = jsonObject.getString("MSG_INFO");
                    opt = jsonObject.getString("OPT_FLAG");
                    arrayList.clear();
                    if ("SUCCESS".equals(opt)) {
                        JSONArray dataarray = jsonObject.getJSONArray("DATA");
                        if (dataarray != null && dataarray.size() > 0) {
                            for (int i = 0; i < dataarray.size(); i++) {
                                arrayList.add(dataarray.getJSONObject(i).getString("WHLOC"));
                            }
                            pihaoedit.setText("");
                            LX="SD";
                            nextbtn.setEnabled(true);
                        }else{
                            nextbtn.setEnabled(false);
                        }

                        quickAdapter.notifyDataSetChanged();
                        quickAdapter.setEmptyView(R.layout.empty, (ViewGroup) recyclerview.getParent());

                    } else {
                        if (TextUtils.isEmpty(msg)) {
                            showSimpleDialog("查询出错");
                        } else {
                            showSimpleDialog(msg);
                        }
                        shadanedit.setText("");
                        nextbtn.setEnabled(false);
                    }

                } catch (Exception e) {
                }
                break;
        }
    }

    private void showSimpleDialog(String message) {
        SimpleDialog.show(this, message);
    }
}
